<?php

namespace app\order\logic;

use think\facade\Db;
use app\api\logic\FreightLogic;
use think\exception\ValidateException;
use app\api\logic\ApiOrdercheckLogic;
use app\api\logic\FeiShuTalkLogic;
use app\api\logic\FeiShuMessageLogic;
use app\data\util\HttpUtil;

class OrderCostLogic
{
    protected $model = null;

    public function __construct()
    {
        
    }

    //计算物流成本
    public function EstimatedCostPerOrder(){
        $t1       = microtime(true);
        $where[]  = ['createtime', '>=', time()-24*3600*3];
        // $where[]  = ['createtime', '>=', strtotime(date('Y-m-d', time() - timezone()))];

        // $update = [];
        // $update['estimate_weight'] = 0;
        // $update['estimate_freight'] = 0;
        // $update['freight_status'] = "";
        // $update = Db::name('order_achievement')
        //     ->where($where)
        //     ->update($update);
        //     halt($update);

        $count = Db::name('order_achievement')
            ->where($where)
            ->where('freight_status',"=","")
            ->count();
            // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('order_id,tracking_number')
                ->where($where)
                ->where('freight_status',"=","")
                ->limit($pageSize)
                ->order('id desc')
                ->select()
                ->toArray();
            foreach ($list as $v){
                //预估物流成本
                $this->add_freight($v);
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }

    //采购
    public function EstimatedCostPerOrderPurchase(){
        $t1       = microtime(true);
        $where[]  = ['c.createtime', '>=', time()-24*3600*3];

        //临时修改
        // $update['material'] = 0;
        // $update = Db::name('order_achievement')
        //     ->alias('a')
        //     ->join('qu_order c','a.order_id = c.order_id', 'left')
        //     ->where('a.shop_id',"=",22)
        //     ->where($where)
        //     ->update($update);
        // halt($update);

        $count = Db::name('order_achievement')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where('a.material',"<=",0)
            ->where($where)
            ->count();
        // halt($count);
            
        $pageSize = 500; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('order_achievement')
                ->field('a.order_id')
                ->alias('a')
                ->join('qu_order c','a.order_id = c.order_id', 'left')
                ->where('a.material',"<=",0)
                // ->where('a.shop_id',"=",17)
                ->where($where)
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();

            $date = date('Y-m', time()); 
            $timedate = strtotime($date);

            foreach ($list['data'] as $v){
                //预估采购成本
                $this->add_material($v,$timedate);
                
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
        
    }

    /**
     *更新订单采购
     */
    public function add_material($order,$timedate)
    {
        $order_quantity = table('order_info')
            ->field('id,spu,sku,quantity')
            ->where('order_id', $order['order_id'])
            ->select()
            ->toarray();
        // halt($order_quantity);
        
        $material = 0;
        //新方法
        if (!empty($order_quantity)) {
            foreach ($order_quantity as $item) {
                if (empty($item['sku'])) {
                    $material = (float)number_format((float)$material + 0.001, 3, '.', '');
                    continue;
                }
                $skucost = table('ordercheck_skucost')
                    ->where('sku', $item['sku'])
                    ->where('timedate', $timedate)
                    ->find(); 
                    
                if(empty($skucost)){
                    $skucost = Db::name('ordercheck_skucost')
                        ->where('sku', $item['sku'])
                        ->where('material_total',">",0)
                        ->order('timedate desc')
                        ->find(); 
                }
                if(empty($skucost)){
                    $spucost = Db::name('ordercheck_spucost')
                        ->where('spu', $item['spu'])
                        ->where('material',">",0)
                        ->order('timedate desc')
                        ->find(); 
                    if(empty($spucost)){
                        $product = Db::name('product')
                            ->where('spu',$item['spu'])
                            ->order('purchase_cost desc')
                            ->find();
                        if(isset($product) && $product['purchase_cost'] > 0.01){
                            $spucost['material'] = $product['purchase_cost'];
                            $spucost['timedate'] = $timedate;
                            $spucost['date'] = date('Y-m', $timedate);
                        }else{
                            // 飞书消息
                            // $FeiShuTalkLogic = new FeiShuTalkLogic();
                            // $msg = $item['spu']."暂无采购成本,请尽快添加";
                            // $FeiShuTalkLogic->send($msg);
                        }
                    }

                    try {
                        
                        $arr_sku['material'] = $spucost['material'];
                        $arr_sku['spu'] = $item['spu'];
                        $arr_sku['sku'] = $item['sku'];
                        $arr_sku['date'] = $spucost['date'];
                        $arr_sku['timedate'] = $spucost['timedate'];
                        $count = (new ApiOrdercheckLogic())->CountTheNumberOfItems($item);
                        $arr_sku['count'] = $count;
                        $arr_sku['material_total'] = (float)number_format((float)$spucost['material'] * $count, 3, '.', '');
                        Db::name('ordercheck_skucost')->insert($arr_sku);
                        $skucost = $arr_sku;

                    } catch (\Throwable $e) {
                        continue;
                    }
                    
                    
                }
                // halt($skucost);

                try {
                        
                    $skucost['material'] = $skucost['material']??0;
                    $skucost['count'] = $skucost['count']??0;
                    $skucost['material_total'] = $skucost['material_total']??0;
                    if ($skucost['count'] == 0) {
                        $count_total = 0;
                    }else{
                        $count_total = (int)number_format((float)$skucost['count']*(int)$item['quantity'], 3, '.', '');
                    }
                    if (!empty($skucost) && $item['quantity'] >= 1) {
                        $newmaterial = (float)number_format((float)$skucost['material_total']*(int)$item['quantity'], 3, '.', '');
                        $material = (float)number_format((float)$material + $newmaterial, 3, '.', '');
                    }
                    //info表新增采购成本明细
                    $update_orderinfo = [
                        'count'   => $skucost['count'],
                        'material'  => $skucost['material'],
                        'count_total'   => $count_total,
                        'material_total'  => (float)number_format((float)$skucost['material_total']*(int)$item['quantity'], 3, '.', ''),
                    ];
                    // halt($update_orderinfo);
                    
                    Db::name('order_info')->where('id',$item['id'])->update($update_orderinfo);
                    
                } catch (\Throwable $e) {
                    continue;
                }
                
            }
        }
        // halt($material);
        $data['material'] = $material;
        $data['material_status'] = "匹配成功";
        //估算开始
        if (empty($material)) {
            $data['material'] = 0;
            $data['material_status'] = "未找到成本";
        }
        
        Db::name('order_achievement')->where('order_id', $order['order_id'])->update($data);
        return true;
    }

    /**
     *更新订单物流
     */
    public function add_freight($order)
    {
        $order_fulfillments = Db::name('order_fulfillments')
            ->where('order_id',$order['order_id'])
            ->select()->toarray();
        if(!empty($order_fulfillments)){
            $ordertransfer['freight'] = 0;
            $ordertransfer['weight'] = 0;
            foreach ($order_fulfillments as $k=>$v) {
                if (!empty($v['tracking_number'])) {
                    $ordertransfer_l = Db::name('ordercheck_logistics')
                        ->field('freight,weight')
                        ->where('transfer_number', $v['tracking_number'])
                        ->order('freight desc')
                        ->find();
                    //方法2---历史数据
                    if(empty($ordertransfer_l)){
                        $ordertransfer_l = Db::name('ordercheck_logistics_copy')
                            ->field('freight,weight')
                            ->where('transfer_number', $v['tracking_number'])
                            ->order('freight desc')
                            ->find();
                    }
                    if(!empty($ordertransfer_l)){
                        $ordertransfer['freight'] = (float)number_format((float)$ordertransfer['freight'] + $ordertransfer_l['freight'], 3, '.', '');
                        $ordertransfer['weight'] = (float)number_format((float)$ordertransfer['weight'] + $ordertransfer_l['weight'], 3, '.', '');
                    }
                }
            }
        }else{
            $ordertransfer = array();
            if (!empty($order['tracking_number'])) {
                //方法2---物流费总和
                // $ordertransfer = Db::name('ordercheck_logistics')
                //     ->field('SUM(freight) as freight')
                //     ->where('transfer_number', $order['tracking_number'])
                //     ->find();
                $ordertransfer = Db::name('ordercheck_logistics')
                    ->field('freight,weight')
                    ->where('transfer_number', $order['tracking_number'])
                    ->order('freight desc')
                    ->find();
                    
                //方法2---历史数据
                if(empty($ordertransfer)){
                    $ordertransfer = Db::name('ordercheck_logistics_copy')
                    ->field('freight,weight')
                    ->where('transfer_number', $order['tracking_number'])
                    ->order('freight desc')
                    ->find();
                }
            }
        }
        // halt($ordertransfer);
        //估算开始
        
            // halt($order);
            try {
                $info = (new FreightLogic())->get_estimate_fee($order['order_id']);
            } catch (ValidateException $e) {
                $info['weight'] = 0;
                $info['fee'] = 0;
            } catch (\Exception $e) {
                $info['weight'] = 0;
                $info['fee'] = 0;
            }

            $infolog['order'] = $order;
            $infolog['info'] = $info;
            htmlLog(['info'=>$infolog],OPERATE_LOG . date('Ym') . '/get_estimate_fee/' . date('Ymd') . '.txt');

            $data['estimate_weight'] = isset($info['weight']) ? $info['weight'] : 0;
            $data['estimate_freight'] = isset($info['fee']) ? $info['fee'] : 0;
            if($data['estimate_weight'] > 0){
                $data['freight'] = 0;
                $data['freight_status'] = "预估物流费";
            }else{
                $data['freight'] = 0;
                $data['freight_status'] = "未找到成本";
            }
        if (!empty($ordertransfer)) {
            if ($ordertransfer['freight'] < 0) {  
                $ordertransfer['freight'] = 0;  
            }
            $data['freight'] = $ordertransfer['freight'];
            $data['freight_weight'] = $ordertransfer['weight'] ?? 0;
            $data['freight_status'] = "匹配成功";
        }
        // halt($data);
        Db::name('order_achievement')->where('order_id', $order['order_id'])->update($data);
        return true;
    }


    /**
    * @desc    广告匹配
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function DailyStatisticsOfAdv_admin($type = 1)
    {  
        $t1       = microtime(true);
        $lastday = date('Y-m-d', strtotime('-2 day') - timezone());
        $endday = date('Y-m-d', strtotime('+1 day') - timezone());
        $midnightYesterday = strtotime($lastday);
        $endOfYesterday  = strtotime($endday);    

        if($type == 1){
            $where[]  = ['a.stat_time', '>=', $midnightYesterday];
            $where[]  = ['a.stat_time', '<=', $endOfYesterday]; 
        }
        if($type == 2){
            $where[] = ['a.admin_id', '=', 0];
            $where[]  = ['a.stat_time', '>=', 1722441600];//从8月1日开始统计
        } 
        if($type == 3){
            $advaccount_admin_log = Db::name('advaccount_admin_log')
                ->field('advertiser_id')
                ->where('operatortime',">",strtotime($lastday))
                ->group('advertiser_id')
                ->select()->toarray();
            if(empty($advaccount_admin_log)){
                return true;
            }
            $advertiser_ids = array_column($advaccount_admin_log, 'advertiser_id');
            $where[] = ['a.advertiser_id', 'in', $advertiser_ids];
            $where[]  = ['a.stat_time', '>=', 1722441600];//从8月1日开始统计
        } 
        $where[] = ['a.spend', '>=', 0.001];
        $where[] = ['a.type', '=', 0];
        // halt($where);
        
        //匹配开始
        $count = Db::name('advertising')  
            ->alias('a')  
            ->where($where) 
            ->count();
            // halt($count);
            
        $executedCount = 0;
        $spendTotal = Db::name('advertising')  
            ->field('  
                a.id,
                a.advertiser_id,
                a.stat_time_day,
                COALESCE(c.admin_id, c2.admin_id) as admin_id_coalesced,
                COALESCE(c.shop_id, c2.shop_id) as shop_id_coalesced
            ')  
            ->alias('a')  
            ->join('qu_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')  
            ->join('qu_advaccount_admin c', '  
                c.advertiser_id = b.advertiser_id AND  
                c.createtime <= a.stat_time AND  
                c.updatetime > a.stat_time AND  
                c.status = 0', 'left')  
            ->join('qu_advaccount_admin c2', '  
                c2.advertiser_id = b.advertiser_id AND  
                c2.createtime <= a.stat_time AND  
                c2.status = 1', 'left')  
            ->where($where) 
            ->group('a.id')
            ->select()->toArray();
        foreach ($spendTotal as $key => $value) {  
            //修改shop_id
            Db::name('advertising')
                ->where('id',$value['id'])
                ->update([
                    'admin_id' => $value['admin_id_coalesced'] ?? 0,
                    'shop_id' => $value['shop_id_coalesced'] ?? 0
                ]);
            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }

        
        if($type !== 2){
            $msg = "没有遗漏";
            echo PHP_EOL . $msg . PHP_EOL;
            return true;
        }

        $where['shop_id'] = 0;
        $inspect = Db::name('advertising')  
            ->field('  
                a.id,
                a.stat_time_day,
                b.info,
                a.advertiser_id,admin_id,shop_id
            ')  
            ->alias('a')  
            ->join('qu_advaccount b', 'b.advertiser_id = a.advertiser_id', 'left')
            ->where($where)  
            ->select()->toArray();
        if(!empty($inspect)){
            $msg = "广告账户分配有遗漏" . PHP_EOL;
            echo PHP_EOL . $msg . PHP_EOL;
            foreach ($inspect as $k=>$v) {
                //包含woobilly
                if(strpos($v['info'], 'woobilly') !== false){
                    continue;
                }
                $msg = $msg. "".$v['stat_time_day']."广告id:" . $v['advertiser_id'] . ',备注：'.$v['info']."" . PHP_EOL;
            }
            if($msg == "广告账户分配有遗漏" . PHP_EOL){
                $msg = "已屏蔽";
                echo PHP_EOL . $msg . PHP_EOL;
                return true;
            }
            // halt($inspect);

            // 飞书消息
            // $FeiShuTalkLogic = new FeiShuTalkLogic();
            // $FeiShuTalkLogic->send($msg);

            // 飞书消息---个人消息
            $FeiShuMessageLogic = new FeiShuMessageLogic();
            $system_admin = Db::name('system_admin')->field('open_id')->where('id',2)->find();
            $open_id = $system_admin['open_id'] ?? 0;
            if($open_id){
                $datamsg = [
                    'message' => $msg,
                    'open_id' => $open_id,
                ];
                $FeiShuMessageLogic->send_message($datamsg);
            }

            //发给负责人
            $system_admin = Db::name('system_admin')->field('open_id')->where('id',28)->find();
            $open_id = $system_admin['open_id'] ?? 0;
            if($open_id){
                $datamsg = [
                    'message' => $msg,
                    'open_id' => $open_id,
                ];
                $FeiShuMessageLogic->send_message($datamsg);
            }
                
        }else{
            $msg = "没有遗漏";
            echo PHP_EOL . $msg . PHP_EOL;
            // halt($msg);
        }

        echo PHP_EOL . "get_webhook_infos-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    
    //售后反馈
    public function AfterSalesFeedback()
    {  
        $t1       = microtime(true);

        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        //匹配开始
        $count = Db::name('order_skuinfo')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.spu')
            ->count();
            // halt($count);
            
        $executedCount = 0;

        $list = Db::name('order_skuinfo')
            ->field('
                a.spu
            ')
            ->alias('a')
            ->join('qu_order c','a.order_id = c.order_id', 'left')
            ->join('qu_order_feedback f','a.spu = f.spu', 'left')
            ->where($where)
            ->group('a.spu')
            ->select()->toArray();
        $OrderReportSkuLogic = new OrderReportSkuLogic();
        foreach ($list as $key => $v) {  
            $OrderFeedbackList = $OrderReportSkuLogic->AfterSalesFeedbackList($v['spu']);
            //售后率，退款率 修改 2024-11-08
            $OrderFeedback                = $OrderFeedbackList[$v['spu']]??[];
            $OrderFeedbackTotal           = $OrderFeedback['OrderFeedbackTotal']??0;
            $RefundTotal                  = $OrderFeedback['RefundTotal']??0;
            $skuquantityTotal             = $OrderFeedback['skuquantity']??0;

            if($skuquantityTotal > 0 && $OrderFeedbackTotal > 0){
            $AfterSalesRate = number_format($OrderFeedbackTotal/$skuquantityTotal*100,3).'%';
            }else{
            $AfterSalesRate = '0.00%';
            }
            if($skuquantityTotal > 0 && $RefundTotal > 0){
            $RefundTotalRate = number_format($RefundTotal/$skuquantityTotal*100,3).'%';
            }else{
            $RefundTotalRate = '0.00%';
            }

            $update['spu']             = $v['spu'];
            $update['AfterSales']      = $OrderFeedbackTotal;
            $update['RefundTotal']     = $RefundTotal;
            $update['AfterSalesRate']  = $AfterSalesRate;
            $update['RefundTotalRate'] = $RefundTotalRate;
            $update['skuquantityTotal'] = $skuquantityTotal;

            $order_feedback = Db::name('order_feedback')->where('spu',$update['spu'])->find();
            if($order_feedback){
                Db::name('order_feedback')->where('spu',$update['spu'])->update($update);
            }else{
                Db::name('order_feedback')->insert($update);
            }

            $executedCount++;
            $num = $count - $executedCount;
            echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条' . PHP_EOL;
        }

        echo PHP_EOL . "order_feedback-定时执行总耗时:" . round(microtime(true) - $t1, 3) . PHP_EOL;
    }
    
    
    //查看是否有新的广告系列
    public function NewAdvertisingCampaign()
    {
        $where = [];
        $where[] = ['time',"=",0];
        $count = Db::name('adv_campaigns')
            ->where($where)
            ->count();
        if($count > 0){
            return true;
        }else{
            return false;
        }
    }

    //手动更新
    public function ViewTodaysUpdates()
    {
        $date = date('Y-m-d', time()-timezone());
        $report_day_cam = Db::name('report_day_cam')->where('date',$date)->find();
        if(empty($report_day_cam)){
            $insert = [
                'date' => $date,
                'status' => 0,
            ];
            Db::name('report_day_cam')->insert($insert);
        }else{
            echo PHP_EOL . "日期".$report_day_cam['date']."已经存在" . PHP_EOL;
        }
    }

    /**
    * @desc    订单发货明细
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function OrderShippingDetails()
    {
        $name = "#1103578";
        $order_achievement = Db::name('order_achievement')
            ->where('name', $name)
            ->find();
        $order_id = $order_achievement['order_id'] ?? 0;
        $shop_id = $order_achievement['shop_id'] ?? 0;

        $shop_info = Db::name('shops')
            ->where('id', $shop_id)
            ->find();
        $url = $shop_info['myshopify_domain'] . "/admin/api/2023-07/orders/".$order_id."/fulfillments.json";
        // halt($url);
        $fulfillments = HttpUtil::getUrl($url, $shop_info);
        halt($fulfillments);
    }
    /**
    * @desc    拉取广告系列
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetAdCampaignsList()
    {
        $where = [];
        $where[] = ['platform_id',"=",1];
        $where[] = ['status',"=",1];
        $where[] = ['info',"like","%shecurve%"];

        $count = Db::name('advaccount')
            ->where($where)
            ->count();
        echo PHP_EOL . "开始更新数据--有".$count."个广告账户" . PHP_EOL;
        if($count <= 0){
            return true;
        }
        // halt($count);
            
        $pageSize = 100; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('advaccount')
                ->where($where)
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            
            foreach ($list['data'] as $v){
                $id = $v['advertiser_id'] ?? "";
                $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
                $token = $fb_token['access_token'];
                $path      = Config('Logisticskey.Facebookad.path');
                $client_secret      = Config('Logisticskey.Facebookad.client_secret');
                $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
                $url = $path.'act_'.$id.'/campaigns?access_token='.$token.'&limit=100&fields=id,name,objective,status,account_id&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
                // halt($url);
                $pages = 1;
                $after = "";
                $this->adsCampaignsinfo($url,$pages,$after);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function adsCampaignsinfo($url,$pages,$after)
    {
        if(!empty($after)){
            $urls = $url . '&after='.$after;
        }else{
            $urls = $url;
        }
        $return = HttpUtil::getUrlFB($urls);
        $return = json_decode($return,true);
        // halt($return);
        $data = $return['data'] ?? [];
        $after = $return['paging']['cursors']['after'] ?? "";
        foreach ($data as $k=>$v) {
            $insert = [
                'advertiser_id' => $v['account_id'] ?? 0,
                'campaign_id' => $v['id'] ?? 0,
                'api_status' => $v['status'] ?? "",
                'name' => $this->removeNonAscii($v['name']),
            ];
            $arr = Db::name('adv_campaignsapi')->where('campaign_id',$insert['campaign_id'])->find();
            if(!$arr){
                Db::name('adv_campaignsapi')->insert($insert);
            }else{
                Db::name('adv_campaignsapi')->where('campaign_id',$insert['campaign_id'])->update($insert);
            }
            echo '更新成功'.$insert['name'].PHP_EOL . '-----' . "循环插入:" . $k . '-----' . PHP_EOL;
        }
        if(!empty($after)){
            echo '开始分页查询'.$pages.PHP_EOL;
            $pages++;
            $this->adsCampaignsinfo($url,$pages,$after);
        }
        return true;
    }
    
    /**
    * @desc    拉取广告
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetAdCinfoList()
    {
        $where = [];
        $where[] = ['platform_id',"=",1];
        $where[] = ['status',"=",1];
        // $where[] = ['advertiser_id',"=",1193228972447900];
        $where[] = ['info',"like","%shecurve%"];

        $count = Db::name('advaccount')
            ->where($where)
            ->count();
        echo PHP_EOL . "开始更新数据--有".$count."个广告账户" . PHP_EOL;
        if($count <= 0){
            return true;
        }
        // halt($count);
            
        $pageSize = 100; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('advaccount')
                ->where($where)
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            
            foreach ($list['data'] as $v){
                $id = $v['advertiser_id'] ?? "";
                $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
                $token = $fb_token['access_token'];
                $path      = Config('Logisticskey.Facebookad.path');
                $client_secret      = Config('Logisticskey.Facebookad.client_secret');
                $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
                $url = $path.'act_'.$id.'/ads?access_token='.$token.'&limit=100&fields=id,name,status,account_id&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
                // halt($url);
                $pages = 1;
                $after = "";
                $this->adsinfo($url,$pages,$after);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function adsinfo($url,$pages,$after)
    {
        if(!empty($after)){
            $urls = $url . '&after='.$after;
        }else{
            $urls = $url;
        }
        $return = HttpUtil::getUrlFB($urls);
        $return = json_decode($return,true);
        $data = $return['data'] ?? [];
        // halt($data);
        $after = $return['paging']['cursors']['after'] ?? "";
        foreach ($data as $k=>$v) {
            $insert = [
                'advertiser_id' => $v['account_id'] ?? 0,
                'adv_id' => $v['id'] ?? 0,
                'api_status' => $v['status'] ?? "",
                'name' => $this->removeNonAscii($v['name']),
            ];
            $arr = Db::name('advapi')->where('adv_id',$insert['adv_id'])->find();
            if(!$arr){
                Db::name('advapi')->insert($insert);
            }else{
                Db::name('advapi')->where('adv_id',$insert['adv_id'])->update($insert);
            }
            echo '更新成功'.$insert['name'].PHP_EOL . '-----' . "循环插入:" . $k . '-----' . PHP_EOL;
        }
        if(!empty($after)){
            echo '开始分页查询'.$pages.PHP_EOL;
            $pages++;
            $this->adsinfo($url,$pages,$after);
        }
        return true;
    }
    

    public function removeNonAscii($string) {  
        $output = '';  
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {  
            $char = mb_substr($string, $i, 1, 'UTF-8');  
            if (ord($char[0]) < 128) {  
                $output .= $char;  
            }  
        }  
        return $output;  
    }  

    //手动更新
    public function Adaccounts_day()
    {
        //三天内的数组
        $report_days = Db::name('report_day_cam')->where('date','>=',date('Y-m-d', strtotime("-2 day")))->order('date desc')->select()->toarray();

        foreach ($report_days as &$report_day) {
            $this->GetAdaccountsInfo($report_day);
            echo PHP_EOL . "日期".$report_day['date']."结束更新数据" . PHP_EOL;
        }
        sleep(1);
        echo PHP_EOL . "完成更新数据" . PHP_EOL;
        sleep(1);
    }

    /**
    * @desc    广告账户花费
    * @author  zhangheng
    */
    public function GetAdaccountsInfo($report_day)
    {
        $date = $report_day['date'] ?? "";
        $start_time = $date;

        $where = [];
        $where[] = ['status',"=",1];

        $count = Db::name('adv_campaigns')
            ->where($where)
            ->count();
        echo PHP_EOL . "开始更新数据--日期:".$start_time."有".$count."个广告账户" . PHP_EOL;
        if($count <= 0){
            return true;
        }
        // halt($count);
            
        $pageSize = 100; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('adv_campaigns')
                ->where($where)
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            
            foreach ($list['data'] as $v){
                $this->GetAdvertising($v,$start_time);
            }
        }
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetAdvertising($advaccount,$date_start)
    {
        $campaign_id = $advaccount['campaign_id'] ?? "";
        $date_end = date('Y-m-d', strtotime($date_start) + 3600*24);

        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$campaign_id.'/insights?access_token='.$token.'&fields=spend,cpc,cpm,impressions,clicks,website_purchase_roas,conversion_values,action_values,conversions,video_play_actions,video_avg_time_watched_actions,video_continuous_2_sec_watched_actions,video_30_sec_watched_actions,video_time_watched_actions,video_p25_watched_actions,video_p50_watched_actions,video_p100_watched_actions,video_play_retention_0_to_15s_actions,video_play_retention_20_to_60s_actions,video_play_retention_graph_actions,video_play_curve_actions,website_ctr,cost_per_conversion&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_end.'"}&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        // halt($return);
        
        if (!empty($return['data']) && isset($return['data'])) {
            foreach ($return['data'] as $va) {
                $insert = [];
                $insert['stat_time'] = strtotime($date_start);
                $insert['stat_time_day'] = date('Y-m-d',strtotime($date_start));
                $insert['adv_name'] = $advaccount['name'] ?? 0;
                //kpop_code
                try{
                    $kpop_code = explode('-',$insert['adv_name']);
                    $insert['kpop_code'] = $kpop_code[2] ?? "";
                }catch(\Exception $e){
                    $insert['kpop_code'] = "";
                }
                
                $insert['api_status'] = $advaccount['api_status'] ?? "";
                $insert['shop_id'] = $advaccount['shop_id'] ?? 0;
                $insert['campaign_id'] = $advaccount['campaign_id'] ?? 0;
                $insert['spend'] = $va['spend'] ?? 0;
                $insert['impressions'] = $va['impressions'] ?? 0;
                $insert['conversions'] = $va['conversions'] ?? 0;
                $insert['cpc'] = $va['cpc'] ?? 0;
                $insert['cpm'] = $va['cpm'] ?? 0;
                $insert['clicks'] = $va['clicks'] ?? 0;
                $insert['createtime'] = time();
                $insert['website_purchase_roas'] = $va['website_purchase_roas'][0]['value'] ?? "";
                $insert['website_ctr'] = $va['website_ctr'][0]['value'] ?? "";
                $insert['video_play_actions'] = $va['video_play_actions'][0]['value'] ?? "";
                $insert['video_avg_time_watched_actions'] = $va['video_avg_time_watched_actions'][0]['value'] ?? "";
                $insert['video_continuous_2_sec_watched_actions'] = $va['video_continuous_2_sec_watched_actions'][0]['value'] ?? "";
                $insert['video_time_watched_actions'] = $va['video_time_watched_actions'][0]['value'] ?? "";
                $insert['video_30_sec_watched_actions'] = $va['video_30_sec_watched_actions'][0]['value'] ?? "";
                $insert['video_p25_watched_actions'] = $va['video_p25_watched_actions'][0]['value'] ?? "";
                $insert['video_p50_watched_actions'] = $va['video_p50_watched_actions'][0]['value'] ?? "";
                $insert['video_p100_watched_actions'] = $va['video_p100_watched_actions'][0]['value'] ?? "";
                $insert['video_play_retention_0_to_15s_actions'] = $va['video_play_retention_0_to_15s_actions'][0]['value'] ?? "";
                $insert['video_play_retention_20_to_60s_actions'] = $va['video_play_retention_20_to_60s_actions'][0]['value'] ?? "";

                $advertising_info = Db::name('adv_campaignsinfo')
                    ->where('campaign_id', $insert['campaign_id'])
                    ->where('stat_time', $insert['stat_time'])
                    ->find();
                if(!empty($advertising_info)){
                    Db::name('adv_campaignsinfo')
                        ->where('campaign_id', $insert['campaign_id'])
                        ->where('stat_time', $insert['stat_time'])
                        ->update($insert);
                }else{
                    Db::name('adv_campaignsinfo')->insert($insert);
                }
            }
            echo "更新花费--广告系列:".$campaign_id."--匹配结果：匹配成功" . PHP_EOL;
            return true;
        }
        $msg = $return['error']['message'] ?? "";
        if(!empty($msg)){
            echo "更新花费--广告系列:".$campaign_id."--匹配结果：匹配失败，失败原因：".$msg . PHP_EOL;
            return true;
        }else{
            echo "更新花费--广告系列:".$campaign_id."--匹配结果：暂无数据" . PHP_EOL;
            return true;
        }
    }

    /**
    * @desc    更新广告系列
    * @author  zhangheng
    */
    public function UpdateAdvCampaign()
    {
        $where = [];
        $where[] = ['name',"like","%-hj%"];

        $count = Db::name('adv_campaignsapi')
            ->where($where)
            ->count();
        echo PHP_EOL . "开始更新数据--".$count."个广告账户" . PHP_EOL;
        if($count <= 0){
            return true;
        }
        // halt($count);
            
        $pageSize = 100; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('adv_campaignsapi')
                ->where($where)
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            
            foreach ($list['data'] as $v){
                $this->GetAdvCampaign($v);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetAdvCampaign($advaccount)
    {
        $update = [];
        $update['type'] = 0;
        $update['campaign_id'] = $advaccount['campaign_id'] ?? "";
        $update['name'] = $advaccount['name'] ?? "";
        if(!empty($update['name'])){
            $update_name = $update['name'];
            //判断name是否符合格式
            if(strpos($update_name,'-') !== false){
                $update_names = explode('-',$update_name);
                $names0 = $update_names[0] ?? '';
                $names1 = $update_names[1] ?? '';
                $names2 = $update_names[2] ?? '';
                if(!empty($names0) && !empty($names1) && !empty($names2)){
                    $spucount = Db::name('ordercheck_spucost')->where('spu',$names1)->count();
                    //转成小写
                    $names2 = strtolower($names2);
                    if($spucount >= 1 && strpos($names2,'hj') !== false){
                        //混剪
                        // 正则判断是否符合-hj
                        $pattern = '/^hj[0-9]+$/';
                        if (preg_match($pattern, $names2)) {
                            // 混剪
                            $update['type'] = 2;
                        }
                    }
                }
            }
        }
        $update['api_status'] = $advaccount['api_status'] ?? "";
        $update['advertiser_id'] = $advaccount['advertiser_id'] ?? "";
        $update['createtime'] = date('Y-m-d H:i:s');
        if($update['type'] !== 2){
            return true;
        }
        // halt($update);
        if(!empty($update['advertiser_id'])){
            $advertising = Db::name('advertising')->where('advertiser_id',$update['advertiser_id'])->where('shop_id',">",0)->order('stat_time_day desc')->find();
            $update['shop_id'] = $advertising['shop_id'] ?? 0;
        }
        // halt($update);
        $adv_campaignsinfo = Db::name('adv_campaigns')
            ->where('campaign_id', $update['campaign_id'])
            ->find();
        if(!empty($adv_campaignsinfo)){
            Db::name('adv_campaigns')
                ->where('campaign_id', $update['campaign_id'])
                ->update($update);
            // echo "广告系列:".$update['campaign_id']."--更新成功" . PHP_EOL;
        }else{
            Db::name('adv_campaigns')
                ->insert($update);
            // echo "广告系列:".$update['campaign_id']."--新增成功" . PHP_EOL;
        }
        return true;
    }

    /**
    * @desc    更新广告
    * @author  zhangheng
    */
    public function UpdateAdvinfo()
    {
        $where = [];
        $where[] = ['name',"like","%-hj%"];

        $count = Db::name('advapi')
            ->where($where)
            ->count();
        echo PHP_EOL . "开始更新数据--".$count."个广告" . PHP_EOL;
        if($count <= 0){
            return true;
        }
        // halt($count);
            
        $pageSize = 100; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        $executedCount = 0;
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('advapi')
                ->where($where)
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            
            foreach ($list['data'] as $v){
                $this->GetAdvinfos($v);
                $executedCount++;
                $num = $count - $executedCount;
                echo PHP_EOL . "总计:" . $count . '条' . '-----' . "已执行:" . $executedCount . '-----' . '剩余:' . $num . '条,当前第' .$i.'页' . PHP_EOL;
            }
        }
    }

    /**
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetAdvinfos($advaccount)
    {
        $update = [];
        $update['type'] = 0;
        $update['adv_id'] = $advaccount['adv_id'] ?? "";
        $update['name'] = $advaccount['name'] ?? "";
        if(!empty($update['name'])){
            $update_name = $update['name'];
            //判断name是否符合格式
            if(strpos($update_name,'-') !== false){
                $update_names = explode('-',$update_name);
                $names0 = $update_names[0] ?? '';
                $names1 = $update_names[1] ?? '';
                $names2 = $update_names[2] ?? '';
                if(!empty($names0) && !empty($names1) && !empty($names2)){
                    $spucount = Db::name('ordercheck_spucost')->where('spu',$names1)->count();
                    //转成小写
                    $names2 = strtolower($names2);
                    if($spucount >= 1 && strpos($names2,'hj') !== false){
                        //混剪
                        // 正则判断是否符合-hj
                        $pattern = '/^hj[0-9]+$/';
                        if (preg_match($pattern, $names2)) {
                            // 混剪
                            $update['type'] = 2;
                        }
                    }
                }
            }
        }
        $update['api_status'] = $advaccount['api_status'] ?? "";
        $update['advertiser_id'] = $advaccount['advertiser_id'] ?? "";
        $update['createtime'] = date('Y-m-d H:i:s');
        if($update['type'] !== 2){
            return true;
        }
        // halt($update);
        if(!empty($update['advertiser_id'])){
            $advertising = Db::name('advertising')->where('advertiser_id',$update['advertiser_id'])->where('shop_id',">",0)->order('stat_time_day desc')->find();
            $update['shop_id'] = $advertising['shop_id'] ?? 0;
        }
        // halt($update);
        $adv_kpops = Db::name('adv_kpop')
            ->where('adv_id', $update['adv_id'])
            ->find();
        if(!empty($adv_kpops)){
            Db::name('adv_kpop')
                ->where('adv_id', $update['adv_id'])
                ->update($update);
        }else{
            Db::name('adv_kpop')
                ->insert($update);
        }
        return true;
    }


    //手动更新广告----两天以内的---fb广告
    public function Adinfoaccounts_day()
    {
        //三天内的数组
        $report_days = Db::name('report_day_cam')->where('date','>=',date('Y-m-d', strtotime("-2 day")))->order('date desc')->select()->toarray();

        foreach ($report_days as &$report_day) {
            $this->GetAdsaccountsInfo($report_day);
            echo PHP_EOL . "日期".$report_day['date']."结束更新数据" . PHP_EOL;
        }
        sleep(1);
        echo PHP_EOL . "完成更新数据" . PHP_EOL;
        sleep(1);
    }

    /**
    * @desc    广告花费
    * @author  zhangheng
    */
    public function GetAdsaccountsInfo($report_day)
    {
        $date = $report_day['date'] ?? "";
        $start_time = $date;

        $where = [];
        $where[] = ['status',"=",1];

        $count = Db::name('adv_kpop')
            ->where($where)
            ->count();
        echo PHP_EOL . "开始更新数据--日期:".$start_time."有".$count."个广告账户" . PHP_EOL;
        if($count <= 0){
            return true;
        }
        // halt($count);
            
        $pageSize = 100; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('adv_kpop')
                ->where($where)
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            
            foreach ($list['data'] as $v){
                $this->GetAdvkpop($v,$start_time);
            }
        }
    }
    

    /**
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function GetAdvkpop($advaccount,$date_start)
    {
        $adv_id = $advaccount['adv_id'] ?? "";
        $date_end = date('Y-m-d', strtotime($date_start) + 3600*24);

        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$adv_id.'/insights?access_token='.$token.'&fields=spend,cpc,cpm,impressions,clicks,website_purchase_roas,conversion_values,action_values,conversions,video_play_actions,video_avg_time_watched_actions,video_continuous_2_sec_watched_actions,video_30_sec_watched_actions,video_time_watched_actions,video_p25_watched_actions,video_p50_watched_actions,video_p100_watched_actions,video_play_retention_0_to_15s_actions,video_play_retention_20_to_60s_actions,video_play_retention_graph_actions,video_play_curve_actions,website_ctr,cost_per_conversion&debug=all&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&time_range={"since":"'.$date_start.'","until":"'.$date_end.'"}&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        // halt($return);
        
        if (!empty($return['data']) && isset($return['data'])) {
            foreach ($return['data'] as $va) {
                $insert = [];
                $insert['stat_time'] = strtotime($date_start);
                $insert['stat_time_day'] = date('Y-m-d',strtotime($date_start));
                $insert['type'] = 2;
                $insert['adv_name'] = $advaccount['name'] ?? 0;
                //kpop_code
                try{
                    $kpop_code = explode('-',$insert['adv_name']);
                    $insert['kpop_code'] = $kpop_code[2] ?? "";
                }catch(\Exception $e){
                    $insert['kpop_code'] = "";
                }

                $insert['api_status'] = $advaccount['api_status'] ?? "";
                $insert['shop_id'] = $advaccount['shop_id'] ?? 0;
                $insert['adv_id'] = $advaccount['adv_id'] ?? 0;
                $insert['spend'] = $va['spend'] ?? 0;
                $insert['impressions'] = $va['impressions'] ?? 0;
                $insert['conversions'] = $va['conversions'] ?? 0;
                $insert['cpc'] = $va['cpc'] ?? 0;
                $insert['cpm'] = $va['cpm'] ?? 0;
                $insert['clicks'] = $va['clicks'] ?? 0;
                $insert['createtime'] = time();
                $insert['website_purchase_roas'] = $va['website_purchase_roas'][0]['value'] ?? "";
                $insert['website_ctr'] = $va['website_ctr'][0]['value'] ?? "";
                $insert['video_play_actions'] = $va['video_play_actions'][0]['value'] ?? "";
                $insert['video_avg_time_watched_actions'] = $va['video_avg_time_watched_actions'][0]['value'] ?? "";
                $insert['video_continuous_2_sec_watched_actions'] = $va['video_continuous_2_sec_watched_actions'][0]['value'] ?? "";
                $insert['video_time_watched_actions'] = $va['video_time_watched_actions'][0]['value'] ?? "";
                $insert['video_30_sec_watched_actions'] = $va['video_30_sec_watched_actions'][0]['value'] ?? "";
                $insert['video_p25_watched_actions'] = $va['video_p25_watched_actions'][0]['value'] ?? "";
                $insert['video_p50_watched_actions'] = $va['video_p50_watched_actions'][0]['value'] ?? "";
                $insert['video_p100_watched_actions'] = $va['video_p100_watched_actions'][0]['value'] ?? "";
                $insert['video_play_retention_0_to_15s_actions'] = $va['video_play_retention_0_to_15s_actions'][0]['value'] ?? "";
                $insert['video_play_retention_20_to_60s_actions'] = $va['video_play_retention_20_to_60s_actions'][0]['value'] ?? "";
                // halt($insert);
                
                $advertising_info = Db::name('adv_campaignsinfo')
                    ->where('adv_id', $insert['adv_id'])
                    ->where('stat_time', $insert['stat_time'])
                    ->find();
                if(!empty($advertising_info)){
                    Db::name('adv_campaignsinfo')
                        ->where('adv_id', $insert['adv_id'])
                        ->where('stat_time', $insert['stat_time'])
                        ->update($insert);
                }else{
                    Db::name('adv_campaignsinfo')->insert($insert);
                }
            }
            echo "更新花费--广告系列:".$insert['adv_id']."--匹配结果：匹配成功" . PHP_EOL;
            return true;
        }
        $msg = $return['error']['message'] ?? "";
        if(!empty($msg)){
            echo "更新花费--广告系列:".$adv_id."--匹配结果：匹配失败，失败原因：".$msg . PHP_EOL;
            return true;
        }else{
            echo "更新花费--广告系列:".$adv_id."--匹配结果：暂无数据" . PHP_EOL;
            return true;
        }
    }
    

    /**
    * @desc    判断广告创意统计
    * @author  zhangheng
    */
    public function JudgingAdvCreativity()
    {
        $where = [];
        $where[]   =  ['kpop_code', '<>', ''];

        $count = Db::name('adv_campaignsinfo')
            ->group('kpop_code')
            ->where($where)
            ->count();
        echo PHP_EOL . "开始更新数据--有".$count."个广告账户" . PHP_EOL;
        if($count <= 0){
            return true;
        }
        // halt($count);
        $fb_token = Db::name('fb_token')->where('type',1)->where('access_token',"<>","")->order("id desc")->find();
        $token = $fb_token['access_token'];

        $pageSize = 100; // 每500条记录读取一次
        $page     = ceil($count / $pageSize);
        for ($i = 1; $i <= $page; $i++){
            $list = Db::name('adv_campaignsinfo')
                ->group('kpop_code')
                ->where($where)
                ->order('id asc')
                ->paginate([  
                    'list_rows' => $pageSize,
                    'page' => $i,
                ])
                ->toArray();
            
        
            foreach ($list['data'] as $v){
                $campaigns = Db::name('adv_campaignsinfo')
                    ->where('kpop_code',$v['kpop_code'])
                    ->group('adv_id')
                    ->select()->toarray();

                $creatives = [];
                $inserts = [];
                foreach ($campaigns as $ka=>$va) {
                    $creative_id = $this->JudgingAdvCreativitys($va['adv_id'],$token);
                    $Advinfo = $this->JudgingAdvinfo($va['adv_id'],$token);
                    $creatives[$creative_id] = $va['adv_id'];
                    //存入数据库
                    $insert = [
                        'adv_id' => $va['adv_id'],
                        'creative_id' => $creative_id,
                        'name' => $v['kpop_code'],
                        'adv_name' => $Advinfo['name'] ?? "",
                        'account_id' => $Advinfo['account_id'] ?? "",
                        'campaign_id' => $Advinfo['campaign_id'] ?? "",
                    ];
                    $inserts[] = $insert;
                }
                Db::name('adv_kpopinfo')->insertAll($inserts);

                if (count($creatives) == 1) {
                    echo $v['kpop_code']."检查完成，无异常".PHP_EOL;
                } else {
                    $msg = $v['kpop_code']."存在不同的creative_id----";
                    foreach ($creatives as $kc=>$vc) {
                        $msg = $msg."广告id:".$vc."--创意id:".$kc.PHP_EOL;
                    }
                    echo $msg.PHP_EOL;
                }
            }
        }
    }

    /**
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function JudgingAdvCreativitys($id,$token)
    {
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.$id.'/adcreatives?access_token='.$token.'&fields=id,name,status&format=json&method=get&pretty=0&suppress_http_code=1&transport=cors&actions=action_device&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        $creative_id = $return['data'][0]['id'] ?? 0;
        return $creative_id;
    }
    /**
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function JudgingAdvinfo($id,$token)
    {
        $path      = Config('Logisticskey.Facebookad.path');
        $client_secret      = Config('Logisticskey.Facebookad.client_secret');
        $appsecret_proof = hash_hmac('sha256', $token,$client_secret);
        $url = $path.''.$id.'?access_token='.$token.'&fields=name,status,account_id,campaign_id&appsecret_proof='.$appsecret_proof;
        // halt($url);
        $return = HttpUtil::getUrlFB($url);
        $return = json_decode($return,true);
        return $return;
    }

}
